<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Figma Metadata Exporter</title>
    <link rel="stylesheet" href="ui.css" />
  </head>
  <body>
    <div id="container">
      <p>选择图层后点击导出按钮</p>
      <button id="export-btn">导出为JSON</button>
    </div>

    <script>
      document.getElementById("export-btn").addEventListener("click", () => {
        // 向主线程发送导出请求
        parent.postMessage({ pluginMessage: { type: "export-json" } }, "*");
        console.log("postMessage");
      });

      // 监听主线程返回的数据
      window.addEventListener("message", (event) => {
        const message = event.data.pluginMessage;

        if (message.type === "export-data") {
          // 创建JSON数据Blob
          const jsonData = JSON.stringify(message.data, null, 2);
          const blob = new Blob([jsonData], { type: "application/json" });
          // 创建下载链接
          const url = URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = "figma-layers.json";
          document.body.appendChild(a);
          a.click();

          // 清理
          setTimeout(() => {
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
          }, 100);
        }
      });
    </script>
  </body>
</html>
